<template>
	<div>
		<Tabs>
			<TabPane label="新增优惠券"></TabPane>
		</Tabs>
		
		<div class="ui-tab-navs">
			<a
				class="ui-tab-navs-cell"
				href="javascript:;"
				v-for="item in types"
				:class="{active: formData.type == item.type, disabled: formData.id && formData.type != item.type}"
				@click="handleChangeType(item.type)"
			>
				<p class="title">{{ item.title }} </p>
				<p class="desc">（{{ item.desc }}）</p>
			</a>
		</div>
		<p style="margin-top: 15px;">注意：一旦选择优惠券类型并新增优惠券成功后，优惠券类型不可变</p>
		<Divider />
		
		<Form ref="form" :model="formData" :rules="rules" label-position="top">
			<FormDescItem label="优惠券名称" prop="name" desc="给优惠券定一个名称，多个优惠券名称不可重复，建议不超过10个字">
				<Input v-model="formData.name" />
			</FormDescItem>
			<FormDescItem label="优惠券描述" desc="">
				<Input v-model="formData.desc" type="textarea" :rows="3" />
			</FormDescItem>
			<FormDescItem label="发放数量" desc="修改优惠券发放总量时只能增加不能减少，请谨慎设置，最多100000000 张">
				<InputNumber v-model="formData.total" :min="1" :step="1" :precision="0" />
			</FormDescItem>
			<FormDescItem label="是否启用" desc="设置优惠券启用状态">
				<RadioGroup v-model="formData.status">
	                <Radio :label="1">是</Radio>
	                <Radio :label="0">否</Radio>
	            </RadioGroup>
			</FormDescItem>
			<FormDescItem label="面额类型" desc="设置优惠券金额类型">
				<RadioGroup v-model="formData.discount_type">
	                <Radio :label="1">固定金额</Radio>
	                <Radio :label="2">随机金额</Radio>
	                <Radio :label="3">固定折扣</Radio>
	            </RadioGroup>
			</FormDescItem>
			<template v-if="formData.discount_type == 1">
				<FormDescItem label="优惠券面额" desc="请输入优惠券面值，必须为正整数，且金额大于0">
					<InputAmount v-model="formData.discount_money" :min="1" :step="1" :precision="0" style="width: 300px;" />
				</FormDescItem>
			</template>
			<template v-if="formData.discount_type == 2">
				<FormDescItem label="优惠券面额" desc="请输入优惠券面值，必须为正整数，且金额大于0(金额最大值不能小于最小值)">
					<InputAmount v-model="formData.discount_min" :min="1" :step="1" :precision="0" :max="formData.discount_max" style="width: 135px;" />
					<span>~</span>
					<InputAmount v-model="formData.discount_max" :min="2" :step="1" :precision="0" style="width: 135px;" />
				</FormDescItem>
			</template>
			<template v-if="formData.discount_type == 3">
				<FormDescItem label="优惠券面额" desc="请输入优惠券面值，必须为正整数，且金额大于0">
					<InputNumber
			            v-model="formData.discount_scale"
			            :max="100"
			            :min="1"
			            :step="1"
			            :precision="0"
			            :formatter="value => `${value} %`"
			            :parser="value => value.replace(' %', '')"
			            style="width: 300px;"
			        >
					</InputNumber>
				</FormDescItem>
			</template>
			<FormDescItem label="使用门槛" prop="amount_limit" desc="设置订单满多少元可使用，勾选不设门槛，则任何金额可用">
				<Input v-model="formData.amount_limit" number :disabled="formData.amount_limit_disabled">
					<template slot="append">
						<Checkbox label="不设门槛" v-model="formData.amount_limit_disabled">不设门槛</Checkbox>
					</template>
				</Input>
			</FormDescItem>
			<FormDescItem label="有效期类型" desc="固定日期在设置的有效期内可用，领取当日后N天以领取时间计算">
				<RadioGroup v-model="formData.indate_type">
	                <Radio :label="2">领取次日N天</Radio>
	                <Radio :label="1">固定日期</Radio>
	            </RadioGroup>
			</FormDescItem>
			<template v-if="formData.indate_type == 2">
				<FormDescItem label="有效期设置" desc="设置优惠券使用限制，如设置所有价格商品可用，则促销商品也可使用">
					<InputNumber v-model="formData.indate_date" :min="1" :step="1" :precision="0" />
				</FormDescItem>
			</template>
			<template v-if="formData.indate_type == 1">
				<FormDescItem label="有效期设置" desc="有效期设置[固定日期]">
					<DatePicker v-model="formData.indate_rangetime" type="datetimerange" placement="top-start"></DatePicker>
				</FormDescItem>
				<FormDescItem label="是否开启提前领取" desc="设置优惠券领取限制，如开启提前领取，则优惠券可在活动开始前提前领取，在活动期间使用">
					<iSwitch v-model="formData.is_advance" size="large" :true-value="1" :false-value="0">
						<span slot="open">开启</span>
						<span slot="close">关闭</span>
					</iSwitch>
				</FormDescItem>
			</template>
			<FormDescItem label="使用限制" desc="固定日期在设置的有效期内可用，领取当日后N天以领取时间计算">
				<RadioGroup v-model="formData.use_limit">
	                <Radio :label="1">仅原价商品可用</Radio>
	                <Radio :label="0">所有价格商品可用</Radio>
	            </RadioGroup>
			</FormDescItem>
		</Form>
		
		<!-- 选择品牌 -->
		<template v-if="formData.type == 2">
			<Divider />
			<p style="margin-bottom: 15px;">设置优惠券参与的品牌，可多选，所选择的品牌均可使用此优惠券</p>
			<Transfer
		        :data="brandLists"
		        :target-keys="targetBrands"
		        :titles="['所有品牌', '参与品牌']"
		        :operations="['撤销品牌', '添加品牌']"
		        :list-style="{width: '250px', height: '260px'}"
		        filterable
		        @on-change="handleChangeBrand"
	        >
	        </Transfer>
		</template>
		
		<!-- 选择品类 -->
		<template v-if="formData.type == 3">
			<Divider />
			<p style="margin-bottom: 15px;">设置优惠券参与的分类，可多选，所选择的分类均可使用此优惠券</p>
			<div style="padding: 5px 10px; width: 320px; height: 360px; border: 1px solid #e1e1e1; overflow: hidden; overflow-y: scroll;">
				<Tree ref="treeElem" :data="categoryLists" show-checkbox></Tree>
			</div>
		</template>
		
		<template v-if="formData.type != 1">
			<Divider />
			<p v-if="formData.type != 4">设置不参与此优惠券的商品，所选择的商品价格金额不会记入优惠券订单使用门槛，如使用门槛设置为不设门槛，此设置无效</p>
			<p v-else>设置优惠券参与的商品</p>
			<div style="margin-top: 15px;">
				<Button type="primary" @click="handleShowGoodsModal">设置商品</Button>
				<Button @click="handleDeleteGoods">删除</Button>
			</div>
			<div v-if="selectedGoods.length > 0" style="margin-top: 15px;">
				<Table
			    	ref="table"
			    	:data="selectedGoods"
			    	:columns="columns"
			    	@on-selection-change="handleChangeSelection"
			    >
			    	<div class="ui-table-cell ui-flex" slot-scope="{ row }" slot="goods">
			    		<ImageCell :src="row.thumb"></ImageCell>
			            <div class="ui-flex-full" style="margin-left: 10px;">
			            	<p class="ui-ellipsis2">{{ row.sku_name }}</p>
			            	<p class="ui-ellipsis ui-text-primary">{{ handleGetSpecTexts(row) }}</p>
			            </div>
			        </div>
			        <div slot-scope="{ row }" slot="price">
			        	<ui-price :value="row.shop_price"></ui-price>
			        </div>
			    </Table>
			</div>
		</template>
		
		<SelectGoods ref="goodsModal" v-model="showGoodsModal" :selected-data="selectedGoods" @on-change="handleChangeGoods"></SelectGoods>
		
		<LoadingMask v-if="loading"></LoadingMask>
		
		<FooterBar>
			<div style="text-align: center;">
				<Button @click="handleBack">返回列表</Button>
				<Button type="primary" @click="handleSubmit" :loading="commiting">保存设置</Button>
			</div>
		</FooterBar>
	</div>
</template>

<script>
import Util from '@/libs/util.js';
import Tools from '@/libs/tools.js';
import FooterBar from '@/components/FooterBar.vue';
import FormDescItem from '@/components/form/FormDescItem.vue';
import InputAmount from '@/components/form/InputAmount.vue';
import SelectGoods from '@/components/SelectGoods.vue';
import ImageCell from '@/components/ImageCell/index.vue';
import LoadingMask from '@/components/LoadingMask.vue';
export default {
	name: 'couponEdit',
	components: {
		FooterBar,
		FormDescItem,
		InputAmount,
		SelectGoods,
		ImageCell,
		LoadingMask
	},
	data() {
		return {
			loading: false,
			commiting: false,
			showGoodsModal: false,
			types: [
				{
					type: 1,
					title: '全场优惠券',
					desc: '全场通用'
				},
				{
					type: 2,
					title: '品牌优惠券',
					desc: '指定品牌使用'
				},
				{
					type: 3,
					title: '分类优惠券',
					desc: '指定分类使用'
				},
				{
					type: 4,
					title: '单品优惠券',
					desc: '指定单品使用'
				}
			],
			ids: [],
			brandLists: [],
			targetBrands: [],
			categoryLists: [],
			selectedGoods: [],
			formData: {
				id: null,
				type: 1,
				name: '',
				desc: '',
				status: 1,
				total: 1,
				discount_type: 1,
				discount_money: 10,		//
				discount_scale: 90,		// type为1时为优惠金额，为3时为折扣
				discount_min: 1,
				discount_max: 10,
				use_limit: 1,			// 使用限制
				indate_type: 2,			// 有效期类型 1 固定日期 2 领取次日N天
				indate_rangetime: [],	// indate[type]为1时，固定日期，需要起始日期
				indate_date: 1,		// indate[type]为2时，领取次日N天
				amount_limit: 1,		// 订单使用门槛金额，0为立减
				amount_limit_disabled: false,
				is_advance: 0,			// 是否提前领取
			},
			rules: {
				name: [
					{required: true, message: '请输入优惠券名称', trigger: 'blur'}
				],
				amount_limit: [
					{type: 'number', message: '请输入数字类型', trigger: 'blur'}
				]
			},
			columns: [
				{
                    type: 'selection',
                    width: 54,
                    align: 'center'
                },
                {
                    title: '商品',
                    slot: 'goods'
                },
                {
                    title: '价格',
                    slot: 'price',
                    maxWidth: 420
                },
                {
                    title: '库存',
                    key: 'number',
                    maxWidth: 300
                }
			]
		}
	},
	computed: {
		brands() {
        	return this.$store.state.app.brands;
        },
        categories() {
        	return this.$store.state.app.categories;
        }
	},
	mounted() {
		//
		this.initBrandData();
		this.initCategoryData();
		
		// 获取品牌数据
    	this.$store.dispatch('getBrandData');
    	// 获取品类数据
    	this.$store.dispatch('getCategoryData');
    	
    	if(this.$route.query.id) {
    		this.formData.id = this.$route.query.id;
    		this.init();
    	}
	},
	watch: {
		brands: {
			deep: true,
			handler() {
				this.initBrandData();
			}
		},
		categories: {
			deep: true,
			handler() {
				this.initCategoryData();
			}
		}
	},
	methods: {
		init() {
			this.loading = true;
			Util.ajax.post(this.API['API_APP_COUPON_DETAIL'], {id: this.formData.id}).then(res => {
				this.loading = false;
				this.formData.type = res.type;
				this.formData.name = res.name;
				this.formData.desc = res.desc;
				this.formData.total = res.total;
				this.formData.status = res.status;
				this.formData.discount_type = res.discount_type;
				this.formData.discount_min = Number(res.discount_min) || 0;
				this.formData.discount_max = Number(res.discount_max) || 0;
				this.formData.discount_money = Number(res.discount_scale) || 0;
				this.formData.discount_scale = Number(res.discount_scale) || 0;
				this.formData.use_limit = res.use_limit;
				this.formData.indate_type = res.indate_type;
				this.formData.indate_date = res.indate_date;
				this.formData.amount_limit = Number(res.amount_limit) || 0;
				this.formData.is_advance = res.is_advance;
				
				if(res.indate_type == 1) {
					this.formData.indate_rangetime = [res.start_time, res.end_time];
				}
				
				// 订单使用门槛为0时，表示无门槛
				if(this.formData.amount_limit <= 0) {
					this.formData.amount_limit_disabled = true;
				}
			}).catch(() => {
				
			})
		},
		initBrandData() {
			if(!this.brands || this.brands.length == 0) {
				this.brandLists = [];
			}else{
				this.brandLists = this.brands.map(item => {
					return {
						key: item.id,
						label: item.name,
						id: item.id,
						name: item.name
					}
				})
			}
		},
		initCategoryData() {
			if(!this.categories || this.categories.length == 0) {
				this.categoryLists = [];
			}else{
				let obj = {
					title: '所有分类',
					expand: true,
					children: this.handleFormatCategory(this.categories)
				}
				this.categoryLists = [obj];
			}
		},
		handleFormatCategory(datas) {
			return datas.map(item => {
				let obj = {
					title: item.label,
					label: item.label,
					value: item.value
				}
				if(item.children && item.children.length > 0) {
					obj.children = this.handleFormatCategory(item.children);
				}
				return obj;
			})
		},
		// 选择优惠券类型
		handleChangeType(type) {
			if(this.formData.id) return false;
			if(this.formData.type == 2) {
				// 重置已选择的品牌
				this.targetBrands = [];
			}else if(this.formData.type == 3) {
				// 重置已选中的品类
				let obj = {
					title: '所有分类',
					expand: true,
					children: this.handleFormatCategory(this.categories)
				}
				this.categoryLists = [obj];
			}
			this.formData.type = type;
			this.selectedGoods = [];
		},
		// 选择品牌
		handleChangeBrand(newTargetKeys) {
			this.targetBrands = newTargetKeys;
		},
		handleGetCheckedCategory(cates) {
			let results = [];
			cates.forEach(item => {
				if(item.checked) {
					results.push(item);
				}else if(item.indeterminate){
					let obj = {
						label: item.label,
						value: item.value
					}
					if(item.children && item.children.length > 0) {
						obj.children = this.handleGetCheckedCategory(item.children);
					}
					results.push(obj);
				}
			})
			return results;
		},
		handleGetCategoryIds(cates, ids) {
			ids = ids || [];
			cates.forEach(item => {
				if(item.checked) {
					ids.push(item.value);
				}else{
					ids = this.handleGetCategoryIds(item.children, ids);
				}
			})
			return ids;
		},
		// 打开选择商品弹窗
		handleShowGoodsModal() {
			let goodsModal = this.$refs.goodsModal;
			// 品牌
			if(this.formData.type == 2) {
				if(this.targetBrands.length == 0) {
					this.$Message.error('请选择参与品牌');
					return false;
				}else{
					let targets = this.targetBrands;
					let brands = this.brandLists.filter(item => {
						return targets.indexOf(item.id) >= 0;
					})
					goodsModal.setBrand(brands, targets);
				}
			}else{
				goodsModal.setBrand();
			}
			// 品类
			if(this.formData.type == 3) {
				let topCate = this.categoryLists[0];
				// 如果顶级分类无选中和子节点选中的情况下，不允许选则商品
				if(!topCate.checked && !topCate.indeterminate) {
					this.$Message.error('请选择参与分类');
					return false;
				}
				let cates = topCate.children;
				// 如果顶级分类是选中状态，表明选择的是所有分类
				if(topCate.checked) {
					goodsModal.setCategory();
				}else{
					// 需要遍历获取已选择的分类
					let items = this.handleGetCheckedCategory(cates);
					let ids = this.handleGetCategoryIds(items);
					goodsModal.setCategory(items, ids);
				}
			}else{
				goodsModal.setCategory();
			}
			this.showGoodsModal = true;
		},
		// 选择的商品
		handleChangeGoods(rows) {
			this.selectedGoods = rows;
		},
		// 格式化规格数据
		handleGetSpecTexts(row) {
			if(Array.isArray(row.spec)) {
				let texts = row.spec.map(item => {
					return item.name +':'+ item.value;
				})
				return texts.join('、');
			}else{
				return row.spec.name +':'+ row.spec.value;
			}
		},
		handleChangeSelection(selection) {
			this.ids = selection.map(item => {
				return item.sku_id;
			})
		},
		// 删除选择的商品
		handleDeleteGoods() {
			if(this.ids.length == 0) {
				this.$Message.error('请至少选择一个商品');
				return false;
			}
			this.selectedGoods = this.selectedGoods.filter(item => {
				return this.ids.indexOf(item.sku_id) < 0;
			})
		},
		// 返回上一级
		handleBack() {
			this.$router.back();
		},
		// 提交
		handleSubmit() {
			this.$refs.form.validate((valid) => {
                if (valid) {
                	let form = this.formData;
                	let topCate = this.categoryLists[0];
                	
                	if(this.commiting) return false;
                	
                	// 验证是否选择日期
                	if(form.indate_type == 1 && form.indate_rangetime.length == 0) {
                		this.$Message.error('请选择优惠券有效期');
						return false;
                	}
                	
                	// 校验品牌、品类、单品
                	if(form.type == 2 && this.targetBrands.length == 0) {
            			this.$Message.error('请选择参与品牌');
						return false;
            		}else if(form.type == 3) {
            			if(!topCate.checked && !topCate.indeterminate) {
            				this.$Message.error('请选择参与品类');
							return false;
            			}
            		}else if(form.type == 4) {
            			if(this.selectedGoods.length == 0) {
                			this.$Message.error('请至少选择一个参与的单品');
							return false;
                		}
            		}
            		
                    let params = {
                    	name: form.name,
                    	type: form.type,
                    	status: form.status,
                    	total: form.total,
                    	desc: form.desc,
                    	discount: {
                    		type: form.discount_type
                    	},
                    	use_limit: form.use_limit,
                    	indate: {
                    		type: form.indate_type
                    	},
                    	amount_limit: (form.amount_limit_disabled ? 0 : form.amount_limit)
                    }
                    
                    // 优惠券类型
                    if(form.discount_type == 1) {
                    	params.discount.scale = form.discount_money;
                    }else if(form.discount_type == 2) {
                    	params.discount.min = form.discount_min;
                    	params.discount.max = form.discount_max;
                    }else{
                    	params.discount.scale = form.discount_scale;
                    }
                    
                    // 有效期类型
                    if(form.indate_type == 1) {
                    	params.indate.date = '';
                    	params.indate.start_time = Tools.formatDate(form.indate_rangetime[0], 'yyyy-MM-dd hh:mm:ss');
                    	params.indate.end_time = Tools.formatDate(form.indate_rangetime[1], 'yyyy-MM-dd hh:mm:ss');
                    	params.is_advance = form.is_advance;
                    }else{
                    	params.indate.date = form.indate_date;
                    	params.indate.start_time = '';
                    	params.indate.end_time = '';
                    	params.is_advance = 0;
                    }
                    
                    // 
                    if(form.type != 1) {
                    	params.rule = {};
                    	let ids = this.selectedGoods.map(item => {
                    		return item.sku_id;
                    	});
                    	if(form.type == 2) {
	                    	params.rule.brand_ids = this.targetBrands;
	                    	params.rule.except_ids = ids;
	                    }else if(form.type == 3) {
	                    	let cates = topCate.children;
	                    	let checkedCates = this.handleGetCheckedCategory(cates);
	                    	params.rule.cat_ids = this.handleGetCategoryIds(checkedCates);
	                    	params.rule.except_ids = ids;
	                    }else if(form.type == 4) {
	                    	params.rule.sku_ids = ids;
	                    }
                    }
                    
                    this.commiting = true;
                    if(form.id) {
                    	params.id = form.id;
                    	Util.ajax.post(this.API['API_APP_COUPON_EDIT'], params).then((res) => {
	                    	this.commiting = false;
	                    	this.$Message.success({
	                    		content: '编辑成功',
	                    		onClose: () => {
	                    			this.handleBack();
	                    		}
	                    	})
	                    }).catch(() => {
	                    	this.commiting = false;
	                    })
                    }else{
                    	Util.ajax.post(this.API['API_APP_COUPON_CREATE'], params).then((res) => {
	                    	this.commiting = false;
	                    	this.$Message.success({
	                    		content: '添加成功',
	                    		onClose: () => {
	                    			this.handleBack();
	                    		}
	                    	})
	                    }).catch(() => {
	                    	this.commiting = false;
	                    })
                    }
                }
            })
		}
	}
}
</script>